package com.woniuxy.gobang84.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import com.woniuxy.gobang84.exception.DAOException;

/**
 * 数据库操作工具类
 *
 * @author 老谭 (<a href="http://www.woniuxy.com">蜗牛学苑</a>)
 *
 */
public class DbUtil {
	private DbUtil() {
	}

	/**
	 * 获取数据库连接(单例模式，整个项目只有一个连接，临时方案)
	 * 
	 * @return
	 */
	private static Connection conn;
	private static String url;
	private static String username;
	private static String password;

	static {

		Properties p = new Properties();
		try {
			p.load(new FileInputStream("db.properties"));  //读取文件
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		url = p.getProperty("url");
		username = p.getProperty("username");
		password = p.getProperty("password");
		System.out.println(url + ";" + username + ";" + password);

		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
//		Connection conn = null;
//		try {
//			conn = DriverManager.getConnection("jdbc:mysql:///wn_chess?serverTimezone=UTC", "root", "123456");
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
		return conn;
	}

	public static void main(String[] args) {
		Connection conn1 = getConnection();
		Connection conn2 = getConnection();
		System.out.println(conn1 == conn2);

	}

	public static void closeConnection(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行insert，update，delete语句的
	 * 
	 * @param sql
	 * @param params
	 */
	public static void execute(String sql, Object... params) {
		Connection conn = getConnection();
		PreparedStatement pstsmt;
		try {
			pstsmt = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pstsmt.setObject((i + 1), params[i]);
			}
			pstsmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException("执行SQL：" + sql + "出错", e);
		} finally {
			// closeConnection(conn);
		}
	}

}
